package com.freestyle.nettychat.chat;

import com.freestyle.netty.easynetty.codes.CustomFrameEncoder;
import com.freestyle.netty.easynetty.codes.JsonMultipleDecode;
import com.freestyle.netty.easynetty.common.Utils;
import com.freestyle.nettychat.chat.dto.*;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.util.ReferenceCountUtil;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by rocklee on 2022/2/5 14:15
 */
public class CodeConsts {
  public static byte[] int2Bytes(int n){
    ByteBuf byteBuf= Unpooled.buffer(4).writeInt(n);
    try{
       return ByteBufUtil.getBytes(byteBuf);
    }
    finally {
      ReferenceCountUtil.release(byteBuf);
    }
  }
  public static final Map<byte[],Class<?>> protocols=new HashMap<byte[], Class<?>>(){{
    put(int2Bytes(100), TextMessage.class);
    put(int2Bytes(101), CommandMessage.class);
   // put(ByteBuffer.allocate(4).putInt(102).array(), AttachmentMessage.class);
    put(int2Bytes(103), LogMessage.class);
    put(int2Bytes(200), JSONData.class);
  }};
  public static CustomFrameEncoder[] createEncoders(){
    List<CustomFrameEncoder> encoders=new LinkedList<>();
    protocols.entrySet().forEach(e->{
      CustomFrameEncoder encoder=new CustomFrameEncoder<>(e.getValue(),e.getKey(), Utils::toJsonBytes);
      encoders.add(encoder);
    });
    return encoders.toArray(new CustomFrameEncoder[0]);
  }
  public static JsonMultipleDecode createMultiDecoder(){
    JsonMultipleDecode jsonMultipleDecode=new JsonMultipleDecode();
    jsonMultipleDecode.registerClasses(protocols);
    return jsonMultipleDecode;
  }
  public static enum MessageType{
    text("text"),
    command("command"),
    attachment("attachment"),
    log("log");
    private final String value;
    MessageType(String value) {
      this.value = value;
    }
    public String getValue(){
      return this.value;
    }
    public static MessageType fromValue(String value){
      for (MessageType i:values()){
        if (i.getValue().equals(value)){
          return i;
        }
      }
      return null;
    }
  }
}
